package by.bucha.testproject.fragments;

import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import by.bucha.tabnavigationproject.R;
import by.bucha.tabnavigationproject.tabsframework.AbstractTabActivity;
import by.bucha.testproject.content.bo.workers.LeaderModel;
import by.bucha.testproject.content.bo.workers.SimpleWorkerModel;
import by.bucha.testproject.content.contract.TaskContract;
import by.bucha.testproject.service.ApplicationService;
import by.bucha.testproject.service.ServiceCallbackListener;
import by.bucha.testproject.service.handlers.BaseHandler;
import by.bucha.testproject.utils.TaskApplication;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class PersonDetailsFragment extends SherlockFragment implements
		ServiceCallbackListener {

	private String mModelId;

	private int mRequestId;

	public static final String EXTRA_MODEL_ID = "id of model which you want edit";

	public static final String EDIT_BACKSTACK_NAME = "edit";

	private TextView mTextName;
	private TextView mTextSurname;
	private TextView mTextPatronymic;
	private TextView mTextSalary;
	private TextView mTextStartTimeReception;
	private TextView mTextEndTimeReception;
	private TextView mTextLunch;
	private TextView mTextWorkspaceNumber;
	private View mView;

	private LinearLayout mLeaderGroup;

	private LinearLayout mSimpleUserGroup;

	public AbstractTabActivity getTabStack() {
		return (AbstractTabActivity) getActivity();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		menu.clear();
		inflater.inflate(R.menu.action_bar_menu_items_fragment_details_person,
				menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_bar_menu_items_fragment_details_person_item_edit:
			changeFragmentToEditPerson();
			return true;
		case R.id.action_bar_menu_items_fragment_details_person_item_back:
			closeFragment();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	public void onPause() {
		super.onPause();
		TaskApplication.getServiceHelper().removeListener(this);
	}

	@Override
	public void onResume() {
		super.onResume();
		TaskApplication.getServiceHelper().addListener(this);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		Log.d(AbstractTabActivity.TAG, "onCreateView in fragment "
				+ getClass().getName());

		setHasOptionsMenu(true);

		Bundle bundle = this.getArguments();
		mModelId = String.valueOf(bundle.getInt(EXTRA_MODEL_ID));

		initViews(inflater, container);

		Uri uri = TaskContract.createUriWithSelection(mModelId,
				TaskContract.WorkerColumns.CONTENT_URI);

		mRequestId = TaskApplication.getServiceHelper().getSingleRow(uri,
				TaskContract.WorkerColumns.WORKER_ID, null, null, null);
		return mView;
	}

	@Override
	public void onServiceCallback(int requestId, Intent requestIntent,
			int resultCode, Bundle data) {

		String action = requestIntent.getAction();
		if (resultCode == BaseHandler.FAILURE_RESPONSE
				&& mRequestId == requestId) {
			Toast.makeText(getActivity().getApplicationContext(),
					data.getString(ApplicationService.EXTRA_ON_ERROR),
					Toast.LENGTH_SHORT).show();
		} else if (ApplicationService.ACTION_QUERY.equals(action)
				&& mRequestId == requestId) {

			String dataType = data
					.getString(TaskContract.WorkerColumns.WORKER_TYPE);

			if (dataType.equals(TaskContract.WorkerColumns.LEADER_TABLE_TYPE)) {
				LeaderModel model = new Gson()
						.fromJson(
								data.getString(ApplicationService.EXTRA_QUERY_RESPONSE),
								new TypeToken<LeaderModel>() {
								}.getType());
				setLeaderModelToView(model);
			} else if (dataType
					.equals(TaskContract.WorkerColumns.SIMPLE_WORKER_TABLE_TYPE)) {
				SimpleWorkerModel model = new Gson()
						.fromJson(
								data.getString(ApplicationService.EXTRA_QUERY_RESPONSE),
								new TypeToken<SimpleWorkerModel>() {
								}.getType());
				setSimpleWorkerModelToView(model);
			}
		}
	}

	private void closeFragment() {
		getActivity().onBackPressed();
	}

	private void setLeaderModelToView(LeaderModel leader) {
		mTextName.setText(leader.getName());

		mTextSurname.setText(leader.getSurname());

		mTextPatronymic.setText(leader.getPatronymic());

		mTextSalary.setText(String.valueOf(leader.getSalary()));

		mSimpleUserGroup.setVisibility(View.GONE);
		mLeaderGroup.setVisibility(View.VISIBLE);

		mTextStartTimeReception.setText(leader.getStartTimeReception());

		mTextEndTimeReception.setText(leader.getEndTimeReception());

		mView.setVisibility(View.VISIBLE);
	}

	private void setSimpleWorkerModelToView(SimpleWorkerModel simpleWorker) {
		mTextName.setText(simpleWorker.getName());

		mTextSurname.setText(simpleWorker.getSurname());

		mTextPatronymic.setText(simpleWorker.getPatronymic());

		mTextSalary.setText(String.valueOf(simpleWorker.getSalary()));

		mSimpleUserGroup.setVisibility(View.VISIBLE);
		mLeaderGroup.setVisibility(View.GONE);

		mTextLunch.setText(simpleWorker.getLunchTime());

		mTextWorkspaceNumber.setText(String.valueOf(simpleWorker
				.getWorkplaceNumber()));
		mView.setVisibility(View.VISIBLE);
	}

	private void initViews(LayoutInflater inflater, ViewGroup container) {
		mView = inflater.inflate(R.layout.view_fragment_person_details,
				container, false);
		mView.setVisibility(View.INVISIBLE);

		mTextName = (TextView) mView
				.findViewById(R.id.view_fragment_person_details_name);

		mTextSurname = (TextView) mView
				.findViewById(R.id.view_fragment_person_details_surname);

		mTextPatronymic = (TextView) mView
				.findViewById(R.id.view_fragment_person_details_patronymic);

		mTextSalary = (TextView) mView
				.findViewById(R.id.view_fragment_person_details_salary);

		mTextStartTimeReception = (TextView) mView
				.findViewById(R.id.view_fragment_person_details_start_time_reception);

		mTextEndTimeReception = (TextView) mView
				.findViewById(R.id.view_fragment_person_details_end_time_reception);

		mTextWorkspaceNumber = (TextView) mView
				.findViewById(R.id.view_fragment_person_details_work_place_number);

		mTextLunch = (TextView) mView
				.findViewById(R.id.view_fragment_person_details_lunch_time);

		mLeaderGroup = (LinearLayout) mView
				.findViewById(R.id.view_fragment_person_details_leader_layout);

		mSimpleUserGroup = (LinearLayout) mView
				.findViewById(R.id.view_fragment_person_details_simple_user_layout);
	}

	public void changeFragmentToEditPerson() {
		// Create fragment and give it an argument specifying the article it
		// should show

		EditPersonFragment newFragment = new EditPersonFragment();

		Bundle arguments = new Bundle();

		arguments.putString(EditPersonFragment.EXTRA_MODEL_ID, mModelId);

		newFragment.setArguments(arguments);

		getTabStack().pushFragment(newFragment);
	}

}
